package com.cip.admin.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cip.admin.service.ImportFileService;
import com.csvreader.CsvReader;
import com.csvreader.CsvWriter;

public class ImportFileServiceImpl implements ImportFileService{
	
	public List<Map<String, String>> getDataFromCSV(File file) throws Exception{
		List<Map<String, String>> csvList= new ArrayList<Map<String,String>>();
		FileReader reader = new FileReader(file);
		CsvReader csvReader = new CsvReader(reader);		
		csvReader.readHeaders();
		String[] headers = csvReader.getHeaders();
		while (csvReader.readRecord())
		{
			Map<String, String> csvValues= new HashMap<String, String>();
			for (String header : headers) {
				csvValues.put(header, csvReader.get(header));
			}
			csvList.add(csvValues);
		}
		return csvList;
		
	}
	
	public File writeDataInCSV(String[] header, List<String[]>records, String fileName) throws Exception{
		//WriteEmptyFile(fileName,"".getBytes());
		File file = new File(fileName);
		if(file.exists()){
			file.delete();
			file = new File(fileName);
		}
		CsvWriter csvOutput = new CsvWriter(new FileWriter(file, true), ',');
		// write out a few records
		csvOutput.writeRecord(header);
		for (String[] strings : records) {
			csvOutput.writeRecord(strings);			
		}
		csvOutput.endRecord();
		csvOutput.flush();
		csvOutput.close();
		return file;
		
	}
	
	
	// helper function to write a byte array into a file
		static public final void WriteEmptyFile(String strFile, byte[] pData)
				throws IOException {
			BufferedOutputStream outStream = new BufferedOutputStream(
					new FileOutputStream(strFile), 32768);
			if (pData.length > 0)
				outStream.write(pData, 0, pData.length);
			outStream.close();
		}

	
	/**
	* Method used to gets all header values liste
	*
	* @param csvFile contains header names
	*
	* @return headerDataAsList as List
	*
	* @throws RttException
	*
	*/
	/*public List<Map<String, String>> readDataFromCSV() throws Exception{
		
		FileReader reader = null;
		CSVReader csvReader = null;	
		List<Map<String, String>> csvList= new ArrayList<Map<String,String>>();
		int count = 0;
		List<String> headers = null;
		try {
			Map<String, String> csvValues= new HashMap<String, String>();
			reader = new FileReader("");
			if(fileFormat.equalsIgnoreCase("Tab")){
				csvReader = new CSVReader(reader,'\t');	
			}else{	
				csvReader = new CSVReader(reader);
			//}	
			String[] nextLineArray = null;	
			boolean first = true;
			while ((nextLineArray = csvReader.readNext()) != null ) {				    
				count++;
				if(first){
					for (String string : nextLineArray) {
						headers.add(string);
					}
				}
				// first line is header  and ArrayIndexof bound Exception occurs when next read line is empty
				if(!first && nextLineArray.length >= 1) {						
					for(int i=0; i < headers.size(); i++) {						
						try{						
							if(nextLineArray[i].equalsIgnoreCase("NULL") || nextLineArray[i].equalsIgnoreCase("\\N")){
								nextLineArray[i] = "";								
							}								
							csvValues.put(headers.get(i), nextLineArray[i]);
							csvList.add(csvValues);
						} catch (ArrayIndexOutOfBoundsException e) {
							// sometimes headers and field values list may not be same
							//to handle that situation only catch the exception
							throw new Exception(e.getMessage(),e);							
						}						
					}						
				continue;
				}
			}
			first = false;
			//logger.debug("createTicketFromCSV1 completed in "+sw.getTotalTimeSeconds());	
		} catch (FileNotFoundException e) {
			throw new FileNotFoundException(e.getMessage());	
		} catch (Exception e) {
			throw new Exception(e.getMessage()+"\t",e);
		}finally{
			try {
				if(reader != null){
					reader.close(); 
				}
                if(csvReader != null){
                 csvReader.close();  
                }	               
           }catch (IOException e) {
              throw new Exception(e.getMessage(),e);
          }
		}
		return csvList;
	}*/

}
